package cn.dgut.FrontLogin;

import cn.dgut.Entity.Student;
import cn.dgut.Utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/FrontLocalLogin")
public class FrontLocalLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = request.getParameter("user");
        String passwd = request.getParameter("passwd");
        String captcha = request.getParameter("captcha");
        int flag = 1;
       /*
       flag = 0 登录成功
       flag = 1 用户名/密码错误
       flag = 2 验证码错误
       */

        String rightCoder = (String) request.getSession().getAttribute("coder");
        //判断验证码
        if(captcha.toLowerCase().equals(rightCoder.toLowerCase())){
            JDBCUtils utils = new JDBCUtils();
            List list = utils.queryAllData("Student");
            for (int i = 0; i < list.size(); i++) {
                Student temp = (Student) list.get(i);
                if(temp.getStudent_name().equals(user.trim())&&temp.getStudent_passwd().equals(passwd.trim())){
                    flag = 0;
                    //登录成功，设置session
                    Map<String, String> info = new HashMap<String, String>();
                    info.put("name", temp.getStudent_name());
                    info.put("id", String.valueOf(temp.getStudent_id()));
                    HttpSession session = request.getSession(true);
                    session.setAttribute("isFrontLogin", info);
                    break;
                }
            }
        }else {
            //验证码错误！！
            flag = 2;
        }

        response.setContentType("application/json,charset=utf-8");
        String strJson = "{\"flag\":\""+flag+"\"}";
        response.getWriter().println(strJson);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}